#version 300 es
uniform mat4 uMVPMatrix ;
uniform mat4 uMMatrix;
uniform vec3 uLightLocation;
uniform vec3 uCamera;
uniform vec3 uLightDirection;

layout (location = 1 ) in vec3 aPosition;
layout (location = 2 ) in vec4 aColor;
in vec3 aNormal;

out vec4 vAmbient;
out vec3 vPosition;  //用于传递给片元着色器的顶点位置
out vec4 vColor;
out vec4 vDiffuse;
out vec4 vSpecular;  //用于传递给片元着色器的􏱶面光最终􏱄度

void point(
in vec3 normal,
inout vec4 diffuse,
in vec3 lightLocation,
in vec4 lightDiffuse
){
vec3 normalTarget=aPosition+normal;
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4 (aPosition,1)).xyz;
newNormal=normalize(newNormal);
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(aPosition,1)).xyz);
vp=normalize(vp);
float nDotViewPosition=max(0.0,dot(newNormal,vp));
diffuse=lightDiffuse*nDotViewPosition;
}

void point2(
in vec3 normal,
inout vec4 specular,
in vec3 lightLocation,
in vec4 lightSpecular
){
vec3 normalTarget=aPosition+normal;  //变化后法向量
vec3 newNormal=(uMMatrix*vec4(normalTarget,1)).xyz-(uMMatrix*vec4(aPosition, 1)).xyz;
newNormal=normalize(newNormal);    //对法向量􏱊􏱱化
vec3 eye= normalize(uCamera-(uMMatrix*vec4(aPosition,1)).xyz);//计算从􏰦面点到摄像机的向量
vec3 vp= normalize(lightLocation-(uMMatrix*vec4(aPosition,1)).xyz);//计算从􏰦面点到光源位置的向量 vp
vp=normalize(vp);//􏱱式化 vp
vec3 halfVector=normalize(vp+eye);//􏱲视线与光线的半向量
float shininess=50.0;//􏱖􏱗粗糙度
float nDotViewHalfVector=dot(newNormal,halfVector);//法线与半向量的点􏱳
float powerFactor=max(0.0,pow(nDotViewHalfVector,shininess));//􏱶镜面反射光强度因子
specular=lightSpecular*powerFactor;//最终的􏱶面光􏱄度
}

void test1(){
    gl_Position = uMVPMatrix * vec4(aPosition , 1) ;
    vec4 diffuseTemp=vec4(0.0,0.0,0.0,0.0);
    point(normalize(aNormal), diffuseTemp, uLightLocation, vec4(0.8,0.8,0.8,1.0));
    vDiffuse=diffuseTemp;
    vPosition = aPosition;
}
void test2(){
    gl_Position = uMVPMatrix * vec4(aPosition , 1) ;
    vec4 specularTemp=vec4(0.0,0.0,0.0,0.0);
    point2(normalize(aNormal), specularTemp, uLightLocation, vec4(0.7,0.7,0.7,1.0));
    vSpecular=specularTemp;
    vPosition = aPosition;
}

void main(){
 test2();
}